﻿using System;
using System.Collections;

namespace FRS_LIB.Devices
{
    public class NETIO_230B : DeviceBase
    {
        private const int OUTPUTS = 4;
        private Telnet.Telnet telnet;

        public NETIO_230B(Device device)
            : this(device.Address, device.Name)
        {
        }

        public NETIO_230B(string address, string name)
            : base(address, name)
        {

            try
            {
                TelnetLogin();
            }
            catch (Exception ex)
            {
                telnet.Close();

                throw ex;
            }

            //telnet.Close();
        }

        private void TelnetLogin()
        {
            /* connect to device using KShell */
            telnet = new Telnet.Telnet();

            telnet.Login(Address, "admin", "admin", 5000);
        }

        public override bool GetOutput(int outputNr)
        {
            Boolean result = false;
            if (outputNr > OUTPUTS - 1)
                throw new Exception(String.Format("Device has only {1} ports!", OUTPUTS));

            string response = TcpSendreceive("port list", 0);
            if ((Convert.ToInt32(GetRotateAnswer(response)) & 1 << outputNr) == 1 << outputNr)
            {
                result = true;
            }
            return result;
        }

        protected override string TcpSendreceive(string command, int port)
        {
            if (telnet.Connected)
                return telnet.SendCommand(command);

            return String.Empty;
        }
       
        public override void SetOutput(int outputNr, int value)
        {
            if (outputNr > OUTPUTS - 1)
                throw new Exception(String.Format("Device has only {1} ports!", OUTPUTS));
            TcpSendreceive(String.Format("port {0} {1}", outputNr + 1, value), 0);
        }

        private string GetRotateAnswer(string response)
        {
            char[] tmp = response.Substring(4).TrimEnd().ToCharArray();
            Array.Reverse(tmp);
            return new String(tmp);

        }
    }

    
}
